package org.i1510.wx.utils;

import java.io.Writer;

import org.i1510.wx.bean.resp.ArticleResp;
import org.i1510.wx.bean.resp.GraphicMessageResp;
import org.i1510.wx.bean.resp.TextMessageResp;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
/**
 * @author Administrator
 * 将回复信息对象转化成xml
 */
public class ObjectToXmlUtils {

	/**
	 * 扩展xstream，使其支持CDATA块
	 */
	public static XStream xstream = new XStream(new XppDriver() {
		public HierarchicalStreamWriter createWriter(Writer out) {
			return new PrettyPrintWriter(out) {
				// 对所有xml节点的转换都增加CDATA标记
				boolean cdata = true;

				@SuppressWarnings("unchecked")
				public void startNode(String name, Class clazz) {
					super.startNode(name, clazz);
				}

				protected void writeText(QuickWriter writer, String text) {
					if (cdata) {
						writer.write("<![CDATA[");
						writer.write(text);
						writer.write("]]>");
					} else {
						writer.write(text);
					}
				}
			};
		}
	});


	/**
	 * TextMessage 转换成xml
	 * @param textMessage
	 * @return
	 */
	public static String textMessageToXml(TextMessageResp textMessage){
		xstream.alias("xml", textMessage.getClass());
		return xstream.toXML(textMessage);
	}
	/**
	*@Author Rambo
	*@Desc：图文消息
	*@param graphicMessage
	*@return TODO
	*@Version  ObjectToXmlUtils.java,v 1.1 2014-10-19 下午11:53:29 
	*/
	public static String graphicMessage(GraphicMessageResp graphicMessage){
		xstream.alias("xml", graphicMessage.getClass());
		xstream.alias("item", new ArticleResp().getClass());
		return xstream.toXML(graphicMessage);
	}
	public static void main(String[] args) {
//		GraphicMessage graphicMessage = new GraphicMessage();
//		
//		
//		String xml = ObjectToXmlUtils.graphicMessage(graphicMessage);
//		XStream xstream2 = new XStream(new DomDriver());
//		xml=xml.replaceAll("xml", "GraphicMessage").replaceAll("item", "Article");
//		System.out.println(xml);
//	
//		
//		GraphicMessage graphicMessage2 =(GraphicMessage)xstream2.fromXML(xml); //xstream.fromXML(xml);
//		List<Article> list2 =graphicMessage2.getArticles();
//		for(int i=0;i<list2.size();i++){
//			Article articleTemp = list2.get(i);
//			System.out.println(articleTemp.getTitle()+"-----"+articleTemp.getUrl());
//			
//		}
		//System.out.println(graphicMessage2.getArticleCount());
	}
}
